﻿using System;
using System.Linq;
using Ayatta.Contract.Domain;
using System.Collections.Generic;

namespace Ayatta.Contract.Extension
{
    public static class ProductExtension
    {
        public static IDictionary<string, string> GetProps(this ProductItem item)
        {
            var dic = new Dictionary<string, string>();

            var names = item.PropertiesName.Split(';');
            var list = names.Select(o => new { Pname = o.Split(':')[2].Trim(), Vname = o.Split(':')[3].Trim() });
            foreach (var o in list.GroupBy(o => o.Pname))
            {
                var key = o.Key;
                var value = string.Join(",", o.Select(x => x.Vname).ToArray());
                dic.Add(key, value);
            }
            return dic;
        }

        public static IDictionary<string, IDictionary<string, string>> GetSaleProps(this IList<Sku> skus)
        {
            var dic = new Dictionary<string, IDictionary<string, string>>();
            if(skus!=null&&skus.Count>0)
            {
                foreach (var sku in skus)
                {
                    var names = sku.PropertiesName.Split(';');
                    var list = names.Select(o => new { Pid = o.Split(':')[0].Trim(), Vid = o.Split(':')[1].Trim(), Pname = o.Split(':')[2].Trim(), Vname = o.Split(':')[3].Trim() });
                    foreach (var o in list.GroupBy(o => o.Pname))
                    {
                        var key = o.Key;
                        var pid = o.First(x => x.Pname == o.Key).Pid;
                        var temp = o.ToDictionary(k => (pid + ":" + k.Vid), v => v.Vname);
                        if (dic.ContainsKey(key))
                        {
                            foreach (var t in from t in temp let x = dic[key] where !x.ContainsKey(t.Key) select t)
                            {
                                dic[key].Add(t.Key, t.Value);
                            }
                        }
                        else
                        {
                            dic[key] = temp;
                        }
                    }
                }
            }
            return dic;
        }
    }
}